package android.pot.com.smartcar.ui.my;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.pot.com.smartcar.MainActivity;
import android.pot.com.smartcar.R;
import android.pot.com.smartcar.action.Action;
import android.pot.com.smartcar.base.BaseFragment;
import android.pot.com.smartcar.base.CommonAdapter;
import android.pot.com.smartcar.base.MyResponseHandler;
import android.pot.com.smartcar.base.ViewHolder;
import android.pot.com.smartcar.entity.CenterEntity;
import android.pot.com.smartcar.entity.MineEntity;
import android.pot.com.smartcar.entity.PlatFormEntity;
import android.pot.com.smartcar.entity.UserInfo;
import android.pot.com.smartcar.fragment.CallDialogView;
import android.pot.com.smartcar.tool.LoadingTool;
import android.pot.com.smartcar.tool.LoginTool;
import android.pot.com.smartcar.ui.my.activity.MyCollectionActivity;
import android.pot.com.smartcar.ui.my.activity.MyHistoryActivity;
import android.pot.com.smartcar.ui.my.activity.MyJoinActivity;
import android.pot.com.smartcar.ui.my.activity.MyOrderActivity;
import android.pot.com.smartcar.ui.my.activity.MyUpdatePwdActivity;
import android.pot.com.smartcar.ui.partner.MyPartNerActivity;
import android.pot.com.smartcar.util.GsonUtil;
import android.pot.com.smartcar.util.TextCheckUtil;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.RelativeSizeSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by zhaoshilu on 2017/11/14.
 */
public class MyFragment extends BaseFragment {

    private static MyFragment instance;

    private View view;

    private Context context;

    private RefreshLayout refreshLayout;

    private ListView listview;

    private CenterEntity centerEntity;

    private TextView tv_phone,tv_save_price;

    private boolean showLoading = true;

    private String business_hours,phone;

    private int new_order_num = 0;

    private PlatFormEntity platFormEntity;

    private CommonAdapter mAdapter;

    public static MyFragment instance() {
        if (instance == null) {
            instance = new MyFragment();
        }
        return instance;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        view = inflater.inflate(R.layout.fragment_my, container, false);
        initView(view);
        addListener();

        return view;

    }

    @Override
    public void onResume() {
        super.onResume();
        initData();
    }

    @Override
    protected void initView(View view) {
        tv_phone = view.findViewById(R.id.tv_phone);
        tv_save_price = view.findViewById(R.id.tv_save_price);
        initListView();
        initRefreshView();
     }

     private void initListView(){
         listview = view.findViewById(R.id.lv_list);
        final List<MineEntity> listData = new ArrayList<>();
         MineEntity entity1 = new MineEntity("我的订单",R.mipmap.img_my_order);
         MineEntity entity2 = new MineEntity("我的收藏",R.mipmap.img_my_collect);
         MineEntity entity3 = new MineEntity("浏览记录",R.mipmap.img_my_see);
         MineEntity entity4 = new MineEntity("合作伙伴",R.mipmap.img_my_partner);
         MineEntity entity5 = new MineEntity("修改密码",R.mipmap.img_my_password);
         MineEntity entity6 = new MineEntity("免费入驻平台",R.mipmap.img_my_enter);
         MineEntity entity7 = new MineEntity("联系我们",R.mipmap.img_my_call);
         listData.add(entity1);
         listData.add(entity2);
         listData.add(entity3);
         listData.add(entity4);
         listData.add(entity5);
         listData.add(entity6);
         listData.add(entity7);
         mAdapter = new CommonAdapter<MineEntity>(context,listData,R.layout.listcell_my_z) {
             @Override
             public void convert(final ViewHolder helper, MineEntity item) {
                 helper.setImageResource(R.id.iv_icon,item.getDrawableRes());
                 helper.setText(R.id.tv_title,item.getTitle());
                 if (item.getTitle().equals("联系我们")){
                     helper.setVisibility(R.id.bottom_line,View.GONE);
                 }else{
                     helper.setVisibility(R.id.bottom_line,View.VISIBLE);
                 }
                 if (item.getTitle().equals("合作伙伴")){
                     if (new_order_num > 0){
                         helper.setVisibility(R.id.tv_point,View.VISIBLE);
                         if(new_order_num>99){
                             helper.setText(R.id.tv_point,"99+");
                         }else {
                             helper.setText(R.id.tv_point, new_order_num + "");
                         }
                     }else{
                         helper.setVisibility(R.id.tv_point,View.GONE);
                     }
                 }
                 helper.setOnClickListener(R.id.out_layout, new View.OnClickListener() {
                     @Override
                     public void onClick(View view) {
                         switch (listData.get(helper.getPosition()).getTitle()){
                             case "我的订单":
                                 startAct(context, MyOrderActivity.class);
                                 break;
                             case "我的收藏":
                                 startAct(context, MyCollectionActivity.class);
                                 break;
                             case "浏览记录":
                                 startAct(context, MyHistoryActivity.class);
                                 break;
                             case "合作伙伴":
                                 if (UserInfo.instance().getDistribution_status() == 0) {//普通用户
                                     CallDialogView dialogView = new CallDialogView(context, "抱歉，您没有权限");
                                     dialogView.show(getActivity().getSupportFragmentManager(), "dialogView");
                                 }else{
                                     startAct(context, MyPartNerActivity.class);
                                 }
                                 break;
                             case "修改密码":
                                 startAct(context, MyUpdatePwdActivity.class);
                                 break;
                             case "免费入驻平台":
                                 if (platFormEntity != null){
                                     Bundle bundle = new Bundle();
                                     bundle.putSerializable("list",platFormEntity);
                                     startAct(context, MyJoinActivity.class,bundle);
                                 }
                                 break;
                             case "联系我们":
                                 if (!TextUtils.isEmpty(phone)) {
                                     CallDialogView dialogViews = new CallDialogView(context, phone, business_hours);
                                     dialogViews.show(getActivity().getSupportFragmentManager(), "dialogViews");
                                     dialogViews.setMethodClickListener(new CallDialogView.OnMethodClickListener() {
                                         @Override
                                         public void methodClick() {
                                             Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phone));
                                             intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                             startActivity(intent);
                                         }
                                     });
                                 }
                                 break;
                         }
                     }
                 });
             }
         };
         listview.setAdapter(mAdapter);
         listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
             @Override
             public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {

             }
         });
     }

    private void initRefreshView() {
        refreshLayout = (RefreshLayout) view.findViewById(R.id.refreshLayout);
        refreshLayout.setEnableLoadMore(false);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                showLoading = false;
                requestData();

            }
        });



    }



    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.context = context;
    }




    @Override
    protected void addListener() {

        view.findViewById(R.id.tv_loginout).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                CallDialogView dialogViews = new CallDialogView(context,"是否退出登录");
                dialogViews.show(getActivity().getSupportFragmentManager(),"dialogViews");
                dialogViews.setMethodClickListener(new CallDialogView.OnMethodClickListener() {
                    @Override
                    public void methodClick( ) {
                        loginOut();

                    }
                });
            }
        });
    }


    @Override
    protected void initData() {
        if (!TextUtils.isEmpty(LoginTool.getToken())){
            requestData();
            getContectData();
            getplatformStationedData();
        }

    }
    private void loginOut(){
        Map<String, String> params = new HashMap<>();
        LoadingTool.StartLoading(context);
        Action.get().memberLogout(context, params, new MyResponseHandler() {
            @Override
            public void onSuccess(String message,JSONObject response) {
                LoadingTool.EndLoading(context);
                LoginTool.setLoginOut(context);
                MainActivity activity = (MainActivity)context;
                activity.changePage(0);
            }
        });

    }

    private void getplatformStationedData(){
        Map<String,String> params = new HashMap<>();

        Action.get().platform_stationed_class(context, params, new MyResponseHandler() {
            @Override
            public void onSuccess(String message,JSONObject response) {
                try {
                    platFormEntity = GsonUtil.getObject(response.toString(), PlatFormEntity.class);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        });
    }
    private void getContectData(){
        Map<String,String> params = new HashMap<>();

        Action.get().contact_us(context, params, new MyResponseHandler() {
            @Override
            public void onSuccess(String message,JSONObject response) {
                try {
                    business_hours = response.getString("business_hours");
                    phone = response.getString("phone");

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

        });
    }
    public SpannableString changTVsize(String value) {
        SpannableString spannableString = new SpannableString(value);
        if (value.contains(".")) {
            spannableString.setSpan(new RelativeSizeSpan(0.8f), value.indexOf("."), value.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        return spannableString;
    }
    private void requestData(){
        Map<String,String> params = new HashMap<>();
//        if (showLoading) {
//            LoadingTool.StartLoading(context);
//        }
        Action.get().personal_center(context, params, new MyResponseHandler() {
            @Override
            public void onSuccess(String message,JSONObject response) {
//                LoadingTool.EndLoading(context);
                centerEntity = GsonUtil.getObject(response.toString(), CenterEntity.class);
                tv_phone.setText("尊敬的："+ TextCheckUtil.CheckString(centerEntity.getPhone()));
                tv_save_price.setText(changTVsize(TextCheckUtil.formate2Money(centerEntity.getSave_money())));
                new_order_num = centerEntity.getNew_order_num();
                mAdapter.notifyDataSetChanged();
                refreshLayout.finishRefresh();
            }

            @Override
            public void onFailure(int statusCode, String error_msg) {
                super.onFailure(statusCode, error_msg);
                refreshLayout.finishRefresh();
                refreshLayout.finishLoadMore();
            }
        });
    }





}